package com.laoba.meishijia.service.impl;

import com.laoba.meishijia.entity.Admin;
import com.laoba.meishijia.exception.LoginException;
import com.laoba.meishijia.mapper.AdminMapper;
import com.laoba.meishijia.processdata.JsonData;
import com.laoba.meishijia.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.net.ssl.HandshakeCompletedEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;

@Service
public class LoginServiceImpl implements LoginService {
    
    @Autowired
    private AdminMapper mapper;
    
    @Override
    public  JsonData login(Admin admin, HttpSession session){
        //数据校验
        
        //从数据库中查数据
        Admin dbAdmin = mapper.findoneByName(admin.getAdminName());
        
        if (dbAdmin == null) {
            //说明用户不存在
//            return new JsonData(1001,"用户不存在");
            throw new LoginException(1001,"用户不存在");
        }
        
        //判断状态
        if(dbAdmin.getAdminStatus()!=null && !(dbAdmin.getAdminStatus().equals(0))){
//            return new JsonData(1001,"用户被锁定,联系管理员");
            throw new LoginException(1002,"用户被锁定,联系管理员");
        }
        
        //判断密码正确
        if(!dbAdmin.getAdminPwd().equals(admin.getAdminPwd())){
//            return new JsonData(1001,"密码错误");
            throw new LoginException(1003,"密码错误");

        }

        //存到session
        session.setAttribute("adminName",admin.getAdminName());

        //更新用户最后登录时间
        dbAdmin.setLastLoginTime(new Timestamp(System.currentTimeMillis()));

        //dbAdmin没有问题
        System.out.println(dbAdmin.toString());

        mapper.update(dbAdmin);


        return new JsonData(200,"登录正常");
        
    }

    @Override
    public  JsonData exit(HttpServletRequest request){
        request.getSession().invalidate();
        return new JsonData(200,"退出正常");
    }
}
